#! /usr/bin/env python3
# coding=utf-8

import os
import sys

from PySide6.QtCore import (QByteArray, QSettings)
from PySide6.QtGui import (QIcon, QAction, QFont)
from PySide6.QtWidgets import (QApplication, QMainWindow,
                               QMessageBox, QTextEdit, QTextBrowser,
                               QToolBar)
from .utils import ExcelPlugin

CurrDir = os.path.dirname(os.path.abspath(__file__))

class MainWindow(QMainWindow):
    def __init__(self, parent=None):
        super().__init__(parent=parent)
        self.setWindowTitle("x01.ExcelHelper")
        self.resize(900, 600)

        self.excel_filename = os.path.join(os.path.expanduser('~'), 'Desktop/temp.txt')  #'.'

        settings = QSettings("x01", "excelhelper")
        if settings.value("excel_filename"):
            self.excel_filename = settings.value("excel_filename")
        if settings.value("MainWindow/Geometry"):
            self.restoreGeometry(QByteArray(settings.value("MainWindow/Geometry")))
        if settings.value("MainWindow/State"):
            self.restoreState(QByteArray(settings.value("MainWindow/State")))

        self.browser = QTextBrowser()
        self.browser.setOpenExternalLinks(True)
        self.setCentralWidget(self.browser)
        # self.readme()

        self.InitActions()
        self.InitPlugins()

        helpMenu = self.menuBar().addMenu("&Help")
        self.AddActions(helpMenu, self.helpActions)

    def readme(self):
        with open(os.path.join(CurrDir, "说明.md"), 'r', encoding='utf-8') as f:
            self.browser.setMarkdown(f.read())

    def InitActions(self):
        aboutAction = self.CreateAction("清理", self.Clear, icon="about", checkable=True)
        helpAction = self.CreateAction("说明", self.Help, icon="help")
        self.helpActions = (helpAction, aboutAction)

    def InitPlugins(self):
        self.excel_plugin = ExcelPlugin(self)
        self.excel_plugin.filename = self.excel_filename
        work_menu = self.menuBar().addMenu("&Excel")
        self.AddActions(work_menu, self.excel_plugin.workActions)

    def closeEvent(self, e):
        settings = QSettings("x01", "excelhelper")
        settings.setValue("excel_filename", self.excel_filename)
        settings.setValue("MainWindow/Geometry", self.saveGeometry())
        settings.setValue("MainWindow/State", self.saveState())

    def CreateAction(
        self,
        text,
        slot=None,
        shortcut=None,
        icon=None,
        tip=None,
        checkable=False,
        signal="triggered",
    ):
        action = QAction(text, self)
        actSignal = None
        if signal == "triggered":
            actSignal = action.triggered
        elif signal == "toggled":
            actSignal = action.toggled
        elif signal == "changed":
            actSignal = action.changed
        elif signal == "hovered":
            actSignal = action.hovered
        else:
            actSignal = action.triggered

        if icon is not None:
            iconpath = os.path.join(CurrDir, "images/" + icon + ".png")
            action.setIcon(QIcon(iconpath))
        else:
            action.icon = None

        if shortcut is not None:
            action.setShortcut(shortcut)
        if tip is not None:
            action.setToolTip(tip)
        if slot is not None:
            actSignal.connect(slot)
        if checkable:
            action.setCheckable(checkable)
        return action

    # help actions

    def Help(self):
        self.readme()

    def Clear(self):
        self.browser.setMarkdown('')

    def AddActions(self, target, actions):
        for action in actions:
            if action is None:
                if not isinstance(target, QToolBar):
                    target.addSeparator()
            elif isinstance(target, QToolBar) and action.icon is None:
                continue
            else:
                target.addAction(action)


def run():
    app = QApplication(sys.argv)
    font = QFont()
    font.setPointSize(14)
    app.setFont(font)
    win = MainWindow()
    win.show()
    sys.exit(app.exec())


if __name__ == "__main__":
    run()
